import { defineStore } from 'pinia'
import { getUserInfo, login, register } from '@/api/user'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    token: localStorage.getItem('token') || '',
    userId: localStorage.getItem('userId') || ''
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    username: (state) => state.userInfo?.username || '',
    creditScore: (state) => state.userInfo?.creditScore || 0,
    isAdmin: (state) => state.userInfo?.role === 'admin'
  },
  
  actions: {
    async login(loginData) {
      try {
        const res = await login(loginData)
        if (res.code === 200 && res.data) {
          this.userInfo = res.data
          this.token = res.data.token || 'mock-token'
          this.userId = res.data.id
          
          localStorage.setItem('token', this.token)
          localStorage.setItem('userId', this.userId)
          localStorage.setItem('user', JSON.stringify(res.data))
          
          return Promise.resolve(res.data)
        }
        return Promise.reject(new Error(res.message || '登录失败'))
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    async register(registerData) {
      try {
        const res = await register(registerData)
        return Promise.resolve(res)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    async getUserInfo() {
      if (!this.userId) {
        return Promise.reject(new Error('用户未登录'))
      }
      
      try {
        const res = await getUserInfo(this.userId)
        if (res.code === 200 && res.data) {
          this.userInfo = res.data
          return Promise.resolve(res.data)
        }
        return Promise.reject(new Error(res.message || '获取用户信息失败'))
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    logout() {
      this.userInfo = null
      this.token = ''
      this.userId = ''
      
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      localStorage.removeItem('user')
      
      ElMessage.success('退出登录成功')
    }
  }
})